package com.hundsun.yr.universal.p2p.ui.fragment;

import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.gyf.barlibrary.ImmersionBar;
import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog;
import com.hundsun.yr.universal.library.widget.HSSegmentControl;
import com.hundsun.yr.universal.library.widget.NoScrollViewPager;
import com.hundsun.yr.universal.p2p.bean.Invested;
import com.hundsun.yr.universal.p2p.bean.ProdTypeBean;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.interactor.impl.ProductSegmentInteractorImpl;
import com.hundsun.yr.universal.p2p.presenter.base.Presenter;
import com.hundsun.yr.universal.p2p.presenter.impl.BaseListEntityPresenterImpl;
import com.hundsun.yr.universal.p2p.presenter.impl.BaseSegmentPresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseFragment;
import com.hundsun.yr.universal.p2p.ui.adapter.SegmentBasePagerAdapter;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.view.base.BaseListView;
import com.hundsun.yr.universal.p2p.view.base.BaseSegmentView;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


/**
 * 投资fragment
 *
 * @version V1.0
 * @Title: ProductFragment.java
 * @Description: 投资-散标投资
 * @date 2015-12-3 上午10:01:08
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class ProductFragment extends BaseFragment implements HSDialog.HSDialogOnItemClickListener, BaseSegmentView,
        HSSegmentControl.OnSegmentControlClickListener, BaseListView {

    private Presenter mPresenter = null;

    private NoScrollViewPager viewpager_product = null;
    /**
     * fragment适配器
     **/
    private SegmentBasePagerAdapter adapter = null;
    private TabLayout tl_product = null;
    private String[] segments;
//    private String[] type;

    /**
     * 设置交易密码的提示
     */
    private HSDialog paypwdDialog = null;

    private BaseListEntityPresenterImpl mPresenter2 = null;
    private String zwgt_data;
    private List<ProdTypeBean> prodTypeBeans = new ArrayList<ProdTypeBean>();
    private LinearLayout ll_product = null;
    private String[] type;
    private int tabWidth;
    private int diviceWidth;


    /**
     * fragment第一次显示时调用，可以用来显示加载刷新数据
     */
    @Override
    protected void onFirstUserVisible() {
//        segments = getResources().getStringArray(R.array.product_types);
//        mPresenter = new BaseSegmentPresenterImpl(mContext, this, new ProductSegmentInteractorImpl(segments));
//        mPresenter.initialized();

        mPresenter2 = new BaseListEntityPresenterImpl(mContext, this, Invested.BASEKEY);
        loadingData();
    }

    /**
     * BaseLazyFragment--相当于fragment的onResume()
     */
    @Override
    protected void onUserVisible() {
        // TODO Auto-generated method stub
        MobclickAgent.onPageStart("ProductFragment");
    }

    /**
     * BaseLazyFragment--相当于fragment的onPause()
     */
    @Override
    protected void onUserInvisible() {
        // TODO Auto-generated method stub
        MobclickAgent.onPageEnd("ProductFragment");
    }

    /**
     * BaseLazyFragment--显示loadingview的视图
     *
     * @return
     */
    @Override
    protected View getLoadingTargetView() {
        ll_product = findView(R.id.ll_product);
        return ll_product;
    }

    /**
     * 初始化p层等操作，设置各种初始化状态
     */
    @Override
    protected void initViewsAndEvents() {
        findview();

        if (ImmersionBar.isSupportStatusBarDarkFont()) { //判断当前设备支不支持状态栏字体变色
            //处理状态栏字体为黑色
            ImmersionBar.with(this).titleBar(R.id.toolbar_title).statusBarDarkFont(true).flymeOSStatusBarFontColor(R.color.black).init();
        } else {
            //处理状态栏有透明度
            ImmersionBar.with(this).titleBar(R.id.toolbar_title).statusBarDarkFont(true).transparentStatusBar().init();
        }
    }

    private void findview() {
        viewpager_product = findView(R.id.viewpager_product);
        tl_product = findView(R.id.tl_product);
    }

    /**
     * 设置当前ui
     **/
    @Override
    protected int getContentViewLayoutID() {
        // TODO Auto-generated method stub
        return R.layout.frag_product;
    }

    /**
     * eventBus的一个回调，哪里发送出来的不知道
     *
     * @param eventCenter
     */
    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {
    }

    /**
     * 确定该ui有eventbus接收
     *
     * @return
     */
    @Override
    protected boolean isBindEventBusHere() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public void onItemClick(Object o, int position) {
    }

    /**
     * 防止按钮连续点击
     */
    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == event.KEYCODE_BACK) {
            if (paypwdDialog != null && paypwdDialog.isShowing()) {
                paypwdDialog.dismiss();
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * 绑定适配器
     *
     * @param viewPager
     * @param fragments
     */
    private void setupViewPager(ViewPager viewPager, List<BaseFragment> fragments) {
        //tablayout的设置
        adapter = new SegmentBasePagerAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        //viewpager和tablayout绑定
        tl_product.setupWithViewPager(viewPager);

        for (int i = 0; i < segments.length; i++) {
            tl_product.getTabAt(i).setText(segments[i]);
        }

        getTabWidth(tl_product);
    }

    @Override
    public void initializeViews(List<BaseFragment> fragments) {
        if (viewpager_product != null) {
            viewpager_product.setOffscreenPageLimit(fragments.size() - 1);
            setupViewPager(viewpager_product, fragments);
        }
    }

    @Override
    public void onSegmentControlClick(int index) {
        viewpager_product.setCurrentItem(index, false);
    }

    public void loadingData() {
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        //投资产品类型
        if (sharedPreferences.getBoolean(UserInfo.ISLOGIN)) {
            mPresenter2.loadingData(TaskConstants.TASK_GETPRODTYPE, getString(R.string.root_url_test) + getString(R.string.api_index_test) + TaskConstants.TASK_GETPRODTYPE, Constants.EVENT_REFRESH_DATA,
                    BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_index_test) + TaskConstants.TASK_GETPRODTYPE, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.
                            getShareProf(UserInfo.TOKENID), zwgt_data), false);
        } else {
            mPresenter2.loadingData(TaskConstants.TASK_GETPRODTYPE, getString(R.string.root_url_test) + getString(R.string.api_index_test) + TaskConstants.TASK_GETPRODTYPE, Constants.EVENT_REFRESH_DATA,
                    BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_index_test) + TaskConstants.TASK_GETPRODTYPE, "", mConfigSP.
                            getShareProf(TaskConstants.TASK_CONFIG), zwgt_data), false);
        }
    }

    @Override
    public <T> void refreshListData(List<T> data) {

    }

    @Override
    public <T> void addMoreListData(List<T> data) {

    }

    @Override
    public <T> void onFailure(String task_name) {
        switch (task_name) {
            case TaskConstants.TASK_GETPRODTYPE:
//                prodTypeBeans.add(new ProdTypeBean("全部", "0"));
//                prodTypeBeans.add(new ProdTypeBean("国投盈", "1"));
//                prodTypeBeans.add(new ProdTypeBean("标保融", "2"));
//                prodTypeBeans.add(new ProdTypeBean("供保融", "3"));
//                prodTypeBeans.add(new ProdTypeBean("车信融", "4"));
//                segments = new String[prodTypeBeans.size()];
//                type = new String[prodTypeBeans.size()];
//
//                for (int i = 0; i < prodTypeBeans.size(); i++) {
//                    segments[i] = prodTypeBeans.get(i).name;
//                    type[i] = prodTypeBeans.get(i).id;
//                }
//
//                mPresenter = new BaseSegmentPresenterImpl(mContext, this, new ProductSegmentInteractorImpl(type));
//                mPresenter.initialized();
                break;
        }
    }

    @Override
    public <T> void initializeViews(String task_name, T result) {
        switch (task_name) {
            case TaskConstants.TASK_GETPRODTYPE:
                if (result == null) {
//                    btn_buy.setEnabled(false);
                    return;
                }

                //刷新精品商品
                List<ProdTypeBean> list = (List<ProdTypeBean>) result;
                //显示数据，刷新数据
                if (list != null && list.size() > 0) {
                    if (list != null) {
                        prodTypeBeans.clear();
                        prodTypeBeans.add(new ProdTypeBean("全部", "0"));
                        prodTypeBeans.addAll(list);
                    }
                    segments = new String[prodTypeBeans.size()];
                    type = new String[prodTypeBeans.size()];

                    for (int i = 0; i < prodTypeBeans.size(); i++) {
                        segments[i] = prodTypeBeans.get(i).name;
                        type[i] = prodTypeBeans.get(i).id;
                    }

                    mPresenter = new BaseSegmentPresenterImpl(mContext, this, new ProductSegmentInteractorImpl(type));
                    mPresenter.initialized();
                }
                break;
        }
    }


    public void getTabWidth(TabLayout tabs) {
        Class<?> tabLayout = tabs.getClass();
        int tabWidth = 0;
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);

            tabs.measure(0,0);
            if (i == 0){
                tabWidth = child.getMeasuredWidth();
            }
//            child.invalidate();
        }

        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        diviceWidth = wm.getDefaultDisplay().getWidth();

        if (tl_product.getTabCount() * tabWidth <= diviceWidth){
            tl_product.setTabMode(TabLayout.MODE_FIXED);
        } else {
            tl_product.setTabMode(TabLayout.MODE_SCROLLABLE);
        }


//        return tabWidth;
    }
}
